'use strict';

var Shop = require('../model/shop.js');
var redisCo = require('../model/redisCo.js');
var WareDao = require('./ware.js');


function* save(json) {
    var entity = new Shop({
        name: inParams.name,
        address: inParams.address,
        telephone: inParams.telephone,
        description: inParams.description,
        images_url: inParams.images_url,
        web_url: inParams.web_url,
        distinct_code: inParams.distinct_code,
        loc: {
            type: "Point",
            coordinates: inParams.distinct_code
        },
        cate_codes: inParams.cate_codes
    });

    console.log(entity);

    var result = yield entity.save();
    return result;
}

function* findById(id) {
    // TODO
}

function* addWare(id, wareInfo) {
    // first query ware
    var wareId = wareInfo.wareId;
    var ware = yield WareDao.findById(wareId);
    // console.log('addWare, ware=',ware);
    var subDoc = {
        category: ware.cateName,
        wareId: wareId
    };
    console.log('addWare, subDoc=', subDoc);

    var query = {
        _id: id
    };
    var update = {
        $push: {
            wareSummery: subDoc
        }
    };


    var result = yield Shop.findOneAndUpdate(query, update).exec();
    console.log(result);
    return result;
}


function* getby(query, order, pageIndex, pageSize) {
    // 如果按距离排序,则采用不同的查询语句
    if (order.by === 'distance') {

    } else {
        // distance
        // var q = {
        // 	loc: {$geoWithin: {$center: [[11, 22], 10000]}},
        // 	"wareSummery.category": {$in: ["eye_care"]}
        // }
        var q = {
            loc: {
                $geoWithin: {
                    $center: [query.srcLoc, query.distance]
                }
            },
            "wareSummery.category": {
                $in: [query.category]
            }
        };

        console.log(q);
        console.log(q.loc['$geoWithin']['$center']);
        console.log(q['wareSummery.category']['$in']);

        var result = yield Shop.find(q).exec();
        console.log(result);
        return result;
    }
}

module.exports.save = save;
module.exports.findById = findById;
module.exports.addWare = addWare;
module.exports.getby = getby;